import psycopg2
from flask import current_app, g
from .config import dbname, host, user, password


def get_db():
    if 'db' not in g:
        conn = psycopg2.connect(
            dbname=dbname,
            host=host,
            user=user,
            password=password
        )
        conn.autocommit = True
        g.db = conn.cursor()

    return g.db


def close_db(e=None):
    db = g.pop('db', None)

    if db is not None:
        db.close()
